from typing import List

import heapq

# 击败了 80% 左右的用户，内存消耗很少
class Twitter:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.tweetMap = dict()
        self.followMap = dict()
        self.time = 0

    def decrAndGetTime(self) -> int:
        self.time -= 1
        return self.time

    def postTweet(self, userId: int, tweetId: int) -> None:
        """
        Compose a new tweet.
        """
        if userId not in self.tweetMap:
            self.tweetMap[userId] = []
        self.tweetMap[userId].append((self.decrAndGetTime(), tweetId))

    def getNewsFeed(self, userId: int) -> List[int]:
        """
        Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent.
        """
        feedSet = self.getFeedSet(userId)
        heap = []
        for uid in feedSet:
            if uid in self.tweetMap:
                for tweetRow in self.tweetMap[uid]:
                    heapq.heappush(heap, tweetRow)

        result = []
        for i in range(10):
            if len(heap) > 0:
                result.append(heapq.heappop(heap)[1])
        return result

    def getFeedSet(self, userId: int) -> set:
        feedSet = {userId}
        if userId in self.followMap:
            feedSet = feedSet.union(self.followMap[userId])
        return feedSet

    def follow(self, followerId: int, followeeId: int) -> None:
        """
        Follower follows a followee. If the operation is invalid, it should be a no-op.
        """
        if followerId not in self.followMap:
            self.followMap[followerId] = set()
        self.followMap[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        """
        Follower unfollows a followee. If the operation is invalid, it should be a no-op.
        """
        if followerId in self.followMap:
            if followeeId in self.followMap[followerId]:
                self.followMap[followerId].remove(followeeId)
